// 在http.js中引入axios
import axios from 'axios'; // 引入axios
import QS from 'qs'; // 序列化post类型的数据
import {Toast} from 'vant';
import router from '@/router/router'
import Vue from 'vue'

// 请求超时时间
axios.defaults.timeout = 20000;
axios.defaults.baseURL = 'https://api.ahlishop.com/'

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

// let token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYTNiMjcxNTM2ZWI1N2U1NzZiMTY0Y2UzMmNhZmY5OTY1ZmVmODQ2ZDUwYmFhZjUxMTUzZjJlNGJmYWM5NjZlZTg0MTY5NjQ1MDQyNGIwYmYiLCJpYXQiOjE2MzM5NDU4NjUsIm5iZiI6MTYzMzk0NTg2NSwiZXhwIjoxNjQ5NjcwNjY1LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.HrdF-Yn032GHcoWJ9dyfcqEqmJ2KTMEOw9_qWaFL5Npjdw5V8A2C0-NKigVxhoFwY1EG2S-y9iWu7CKS2yDeJ1zw_q4G1uvUJ0v5Dw_KO27nlQy7uOm2EdrXTJdAhViQ2SFco-m3IKfGye9NiX0TL5OAu_MMnZZeJa2K2avquVbMxISRUHExoQS6IYHWkpJCc0G9AhrO4-diL0BmLfP9lO7jvZuxh-LarEl65c-cROtWu0wamJexO97plEH_CJN7r7gBLMKHF-BIuZl_YwPaJjhcADN05txc91ox6vwzOqtBjxeFWZlfhDKY75bUnrQamet88OJmoC5HTxZrNOkZ3VHwIVfl0GKfefdILP-_6otC2Zxik86rbLGwOHkb9mW-3ls_f3_vN6qFazrExfmrgv9Yz4H4Vs4m-2L-iT5hLqVE92JR8XDHyzowNxNPR0DZUV8s0IRLXPBx8JaGb10SVMe8nDhLbl1RXQ7L34oo9-Lf3yDDm3MNaZhdE7yqmEUDtgN7eAAx-gw5CHAvMlLbTGBXNSuNprI4oeo89mDWLVf-9Lv3j-xS0BxEQQEzp4_gZrsF2PHRxccru1SsYmIYrtAYjW2i5AHL_jDUhhQYVuzAL20AvzfpmoQG842CAAHkZ84aEU6Pwg2fvuvaSUGxFCe-uR7Fz8Ovv9nlrfPmli4'

axios.interceptors.request.use(config =>{
    const pathNotNeedToken = [
        'api/auth/login', 'api/auth/sendVerifyCode', 'api/auth/checkVerifyCode', 'api/auth/forgotPassword'
    ]
    let needToken = true
    pathNotNeedToken.forEach(path => {
        if (config.url === path) {
            needToken = false
        }
    })
    if (needToken) {
        const access_token = localStorage.getItem("token")
        if (access_token) {
            config.headers.Authorization = 'Bearer ' + access_token
        } else {
            router.replace({ path: '/login/roleChoose'});
        }
    }
    return config
})
// 响应拦截器
axios.interceptors.response.use(
    response => {
        // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
        // 否则的话抛出错误
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是2开头的的情况
    // 这里可以跟你们的后台开发人员协商好统一的错误状态码
    // 然后根据返回的状态码进行一些操作，例如登录过期提示，错误提示等等
    // 下面列举几个常见的操作，其他需求可自行扩展
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登录
                // 未登录则跳转登录页面，并携带当前页面的路径
                // 在登录成功后返回当前页面，这一步需要在登录页操作。
                // case 401:
                //     router.replace({
                //         path: '/login/roleChoose',
                //         query: {
                //             redirect: router.currentRoute.fullPath
                //         }
                //     });
                //     break;

                // 403 token过期
                // 登录过期对用户进行提示
                // 清除本地token和清空vuex中token对象
                // 跳转登录页面
                // case 403:
                //     Toast({
                //         message: '登录过期，请重新登录',
                //         duration: 1000,
                //         forbidClick: true
                //     });
                //     // 清除token
                //     localStorage.removeItem('token');
                //     // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
                //     setTimeout(() => {
                //         router.replace({
                //             path: '/login/roleChoose',
                //             query: {
                //                 redirect: router.currentRoute.fullPath
                //             }
                //         });
                //     }, 1000);
                //     break;

                // 404请求不存在
                case 404:
                    Toast({
                        message: '网络请求不存在',
                        duration: 1500,
                        forbidClick: true
                    });
                    break;
                // 其他错误，直接抛出错误提示
                default:
                    Toast({
                        message: error.response.data.message,
                        duration: 1500,
                        forbidClick: true
                    });
            }
            return Promise.reject(error.response);
        }
    }
);

export function get(url , params) {
    let path = getPath(url, params)
    return new Promise((resolve, reject) => {
        axios.get(path, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    });
}

export function post(url, params) {
    let path = getPath(url, params)
    return new Promise((resolve, reject) => {
        axios.post(path, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

export function put(url , params) {
    let path = getPath(url, params)
    return new Promise((resolve, reject) => {
        axios.put(path, params).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    });
}

export function del(url , params) {
    let path = getPath(url, params)
    return new Promise((resolve, reject) => {
        axios.delete(path, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    });
}

export function postByFormData(url, params) {
    return new Promise((resolve, reject) => {
        QS.stringify(params)
        axios.post(url, params, {headers:{'Content-Type': 'multipart/form-data'}})
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}


const getPath =(url , params) => {
    let path = url
    if (params && params.pathParam){
        path = url + '/' + params.pathParam
        Vue.delete(params, 'pathParam')
    }
    return path
}